package com.best.oasis.settlement.web.exception;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.flex.security.SecurityExceptionTranslator;
import org.springframework.security.AuthenticationCredentialsNotFoundException;
import org.springframework.security.BadCredentialsException;

import com.best.oasis.settlement.common.error.ErrorCode;
import com.best.oasis.settlement.service.base.BusinessException;

import flex.messaging.MessageException;


/**
 * @author BL00064
 *
 */
public class MyExceptionTranslator extends SecurityExceptionTranslator{
	/**
	 * Logger for this class
	 */
	private static final Log logger = LogFactory.getLog(MyExceptionTranslator.class);
	

	@Override
	public boolean handles(Class<?> clazz) {
		return true;
	}

	@Override
	public MessageException translate(Throwable t) {
		if(t instanceof AuthenticationCredentialsNotFoundException
				|| t.getCause() instanceof AuthenticationCredentialsNotFoundException){
			//not logined
			MessageException me = new MessageException(ErrorCode.NOT_LOGINED);
			return me;
		}else if(t instanceof ActionException){
			if(isAbnormalException(t)){
				logger.warn("translate(Throwable)", t);
			}else{
				logger.warn("translate(Throwable)" + t.getMessage());
			}
			return new MessageException(t.getCause().getMessage());
		}else if(t instanceof BusinessException){
			//有字段校验出错的异常需要把字段出错的信息返回到flex客户端去
			BusinessException be = (BusinessException)t;
			if(be.hasFieldError()){
				return super.translate(t);
			}
			/*if(isAbnormalException(t)){
				logger.warn("translate(Throwable)", t);
			}else{
				logger.warn("translate(Throwable)" + t.getMessage());
			}*/
			logger.warn(be.getMessage());
			return new MessageException(t.getMessage());
		}else if(t instanceof BadCredentialsException){
			logger.info(t);
		}else{
			logger.error("translate(Throwable)", t); //$NON-NLS-1$
		}
		return super.translate(t);
	}
	/**
	 * 是否为古怪的错误
	 * @param t
	 * @return
	 */
	private boolean isAbnormalException(Throwable t){
		if(t.getCause() instanceof SecurityException 
				|| t.getCause() instanceof BusinessException){
			return false;
		}else{
			return true;
		}
	}
}
